package org.skydiveapplibrary.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.skydiveapplibrary.R;
import org.skydiveapplibrary.data.LogEntryImage;
import org.skydiveapplibrary.data.Signature;
import org.skydiveapplibrary.repository.LogEntryRepository;
import org.skydiveapplibrary.repository.SignatureRepository;
import org.skydiveapplibrary.util.ImportTask.TaskProgress;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.widget.Toast;

public class StorageTransferTask extends AsyncTask<Void, ImportTask.TaskProgress, Integer>
{
	// results types
	public static final int SUCCESS = 13;
	public static final int ERROR = 23;

	private Context mContext;
	private FileManager mFileManager;
	private LogEntryRepository logEntryRepository;
	private SignatureRepository signatureRepository;
	private ProgressDialog mProgressDialog = null;

	public StorageTransferTask(Context context)
	{
		mContext = context;
		mFileManager = new FileManager(context);
		logEntryRepository = new LogEntryRepository(context);
		signatureRepository = new SignatureRepository(context);
	}
	
	@Override
	protected void onPreExecute()
	{		
		// show dialog
		mProgressDialog = new ProgressDialog(new ContextThemeWrapper(mContext, R.style.DialogStyle));
		mProgressDialog.setTitle("Transferring Images");
        mProgressDialog.setMessage("");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
	}

	@Override
	protected Integer doInBackground(Void... params)
	{
		int result = SUCCESS;
		String message;
		
		// Store Old Files
		List<File> oldFiles = new ArrayList<File>();		
		
		try
		{
			publishProgress(new TaskProgress(0, "Preparing"));
			
			// Get Signatures
			List<Signature> signatures = signatureRepository.getSignatures();
			
			// Get LogEntryImages
			List<LogEntryImage> images = logEntryRepository.getAllLogEntryImages();
			
			// Copy Signatures
			message = "Copying signatures";
			for (int i = 0 ; i < signatures.size() ; i++)
			{
				publishProgress(new TaskProgress(
						(int) ((i / (float) signatures.size()) * 100),
						message));
				
				File srcFile = mFileManager.getStorageFile(
						signatures.get(i).getFilename(),
						!mFileManager.getUseExternalStorage());
				
				File destFile = mFileManager.getStorageFile(
						signatures.get(i).getFilename(),
						mFileManager.getUseExternalStorage());
				
				mFileManager.copyFile(srcFile, destFile);
				oldFiles.add(srcFile);
			}
			
			// Copy LogEntryImages
			message = "Copying images";
			for (int i = 0 ; i < images.size() ; i++)
			{
				publishProgress(new TaskProgress(
						(int) ((i / (float) images.size()) * 100),
						message));
				
				File srcFile = mFileManager.getStorageFile(
						images.get(i).getFilename(),
						!mFileManager.getUseExternalStorage());
				
				File destFile = mFileManager.getStorageFile(
						images.get(i).getFilename(),
						mFileManager.getUseExternalStorage());

				mFileManager.copyFile(srcFile, destFile);
				oldFiles.add(srcFile);
			}
		}
		catch (Exception ex)
		{
			message = ex.getMessage();
			message = message == null ? ex.toString() : message;
			Log.e(StorageTransferTask.class.getCanonicalName(), message);
			result = ERROR;
		}
		
		// If all files were copied the transfer is a success
		// Whether the cleanup fails or not images on the selected
		// storage should still be used.
		
		if (result == SUCCESS)
		{
			try
			{
				// Delete Old Files
				message = "Deleting unused filess";
				for (int i = 0 ; i < oldFiles.size() ; i++)
				{
					publishProgress(new TaskProgress(
							(int) ((i / (float) oldFiles.size()) * 100),
							message));
					
					oldFiles.get(i).delete();
				}
			}
			catch (Exception ex)
			{
			}
		}
		
		return result;
	}

	@Override
	protected void onPostExecute(Integer result)
	{
		// dismiss dialog
		mProgressDialog.dismiss();

		// get resource for result
		int resourceId = result == SUCCESS ? R.string.settings_transfer_success
			: R.string.settings_transfer_error;

		// show toast
		Toast status = Toast.makeText(mContext, resourceId, Toast.LENGTH_SHORT);
		status.show();
	}

	protected void setProgressMessage(TaskProgress progress)
	{
		mProgressDialog.setProgress(progress.percentage);
		mProgressDialog.setMessage(progress.message);
	}
	
	@Override
	protected void onProgressUpdate(TaskProgress... progress)
	{
		setProgressMessage(progress[0]);
    }
}